package com.pan.script.util;

import java.awt.*;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public enum ScriptUtil {
    INSTANCE;


    {


    }

    private final String resourceScriptPath = "\\script";


    /**
     * 如果不存在对应的文件名则返回空值
     * @param fileName
     * @return
     */
    private URL getResourceScript(String fileName){
        fileName = fileName.replaceAll("^[\\.\\\\/]+","");
        URL targetUrl = ClassLoader
                .getSystemResource(resourceScriptPath + "\\" + fileName);
        return targetUrl;
    }


    public List<String> findAll() {
        URL resourceScriptUrl = getResourceScript("");
        List<String> resultList = new ArrayList<>();
        try {
            File file = new File(resourceScriptUrl.toURI());
            l0:
            for (String name : file.list())
                if (name.endsWith(".z1f"))
                    resultList.add(name);
                else
                    continue l0;
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        return resultList;
    }

    public InputStream getScriptInputStream(String scriptName){
        URL scriptUrl = getResourceScript(scriptName);
        if (scriptUrl == null)
            throw new RuntimeException("Error: Not found script "+ scriptName);
        InputStream scriptInputStream;
        try {
            File file = new File(scriptUrl.toURI());
            scriptInputStream = new FileInputStream(file);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return scriptInputStream;
    }

    public static void main(String[] args) throws AWTException {
        System.out.println(INSTANCE.getResourceScript(""));

//        InputStream scriptStream = ClassLoader.getSystemResourceAsStream("script\\Hello.zzz");
//        BufferedReader reader = new BufferedReader(new InputStreamReader(scriptStream));
//        String[] lines = reader.lines().toArray(String[]::new);
//        ScriptTranslators panTranslators = new PanScriptTranslators();
//        Strategy strategy = panTranslators.to(lines);
//
//        Robot robot = new Robot();
//        strategy.action(robot);

    }

}
